package com.software.levelupandroid.taskIssue.view.label;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.software.levelupandroid.entity.Label;
import com.software.levelupandroid.entity.Resource;
import com.software.levelupandroid.home.CallBack;


import java.util.List;


public class LabelViewModel extends ViewModel {
    private final MutableLiveData<Resource<List<Label>>> labelListLiveData;

    public LabelViewModel(){
        labelListLiveData = new MutableLiveData<>();
    }

    public LiveData<Resource<List<Label>>> getLabelLiveData(){
        return labelListLiveData;
    }

    public void getLabel(Context context) {
        LabelRepository.getLabelRepository().getLabelByPriority(new CallBack<List<Label>>() {

            @Override
            public void onSuccess(List<Label> data) {
                runOnMainThread(labelListLiveData, Resource.success(data));
            }

            @Override
            public void onFailure(String msg) {
                Log.e("home:", msg);
                runOnMainThread(labelListLiveData, Resource.failure(msg, null));
            }
        },context);
    }
    /**
     * 将LiveData的赋值放在主线程上
     * @param labelListLiveData
     * @param data
     */
    private void runOnMainThread(MutableLiveData<Resource<List<Label>>> labelListLiveData, Resource<List<Label>> data) {
        if (Looper.myLooper() == Looper.getMainLooper())
            //当前线程在主线程
            labelListLiveData.setValue(data);
        else
            //当前线程不在主线程
            labelListLiveData.postValue(data);
    }

}
